package cn.cqzaier.pub.api;/**
 * @author: zehua
 * @date: 2022/5/16 15:56
 * @description:
 */

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;

/**
 * @author zehua
 * @date 2022/5/16
 * 公共api调用
 */
@Slf4j
public class RequestApiUtil<T extends ReqPublicCommon,R> {
    /**
     * @param url 请求地址
     * @param function 请求还回处理逻辑
     * @return
     */
    public  R requestGet(String url, Function<String,R> function,Map<String,Object> paramMap){
//        log.info("requestGet-url:{}-param:{}",url,JSON.toJSONString(paramMap));
        String s = HttpUtil.get(url, paramMap);
//        log.info("requestGet:{}",s);
         return function.apply(s);
    }


    public  R okrequestGet(String url, Function<String,R> function){
        String s = "";
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).removeHeader("User-Agent").addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0").build();
        try {
             s = httpClient.newCall(request).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return function.apply(s);

    }


    /**
     * @param url 请求地址
     * @param t 请求参数
     * @param function 请求还回处理逻辑
     * @return
     */
    public  R requestGet(String url, T t,Function<String,R> function){
        String jsonStr = JSON.toJSONString(t);
        final TreeMap requestPramMap = JSONObject.parseObject(jsonStr, TreeMap.class);
        return (R)requestGet(url,function,requestPramMap);
    }


    /**
     * @param url 请求地址
     * @param function 请求还回处理逻辑
     * @return
     */
    public  R requestPost(String url, Function<String,R> function, Object obj){
        Map map = JSONUtil.toBean(JSON.toJSONString(obj), Map.class);
        log.info("requestPost-url:{}-param:{}",url,JSON.toJSONString(map));
        String s = HttpUtil.post(url, map);
        log.info("requestPost:{}",s);
        return function.apply(s);
    }

   /* public  R requestGet(String url, Map<String,Object> param,Function<String,R> function){
        param.putAll(commonParam);
        param.put("sign", SignMD5Util.getSignStr(param,DataokeApiConstants.APP_SECRET));
        log.info("requestGet-url:{}-param:{}",url,JSON.toJSONString(param));
        String s = HttpUtil.get(url, commonParam);
        log.info("requestGet:{}",s);
        return function.apply(s);
    }*/









}